/*
 * @Author: zhang_gen_yuan
 * @Date: 2020-12-15 21:52:46
 * @LastEditTime: 2020-12-15 22:16:14
 * @Descripttion: 
 */


function reactive(obj) {
    if (typeof obj === 'object') {
        if (obj instanceof Array) {
            obj.forEach((item, index) => {
                if(typeof item === 'object'){
                    obj[index] = reactive(item)
                }
            })
        } else {
            for (let key in obj) {
                let item = obj[key];
                obj[key] = reactive(item)
            }
        }

        return new Proxy(obj,{
            get(obj,key,receiver){
                return Reflect.get(...arguments)
            },
            set(obj,key,val,receiver){
                console.log('更新UI')
                return Reflect.set(...arguments)
            }
        })

    } else {
        console.log(`${obj} not a object`)
    }
}


let obj = {
    a:'a',
    b:{
        c:'c',
        d:{
            e:'e',
            f:{
                g:'g'
            }
        }
    }
}

let state = reactive(obj);
state.a = 1;
state.b.c = 2;
state.b.d.e = 3;
state.b.d.f.g = 4;
console.log(state)

let arr = [{name:'张三',age:18},{name:'李四',age:28}];

let state1 = reactive(arr);
// console.log(state1)
// state1[0].name = "王五";
// state1[1].name = "马六";
state1[2] = {
    name:'添加了一个'
}
console.log(state1)